<template>
  <el-dialog :title="!searchForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="searchForm" :rules="dataRule" ref="searchForm" @keyup.enter.native="searchFormSubmit()"
             label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="searchForm.name" placeholder="组织机构名称"></el-input>
        <!--        <el-select v-model="searchForm.name" placeholder="组织机构名称"  v-if="searchForm.id">-->
        <!--          <el-option-->
        <!--            v-for="item in departmentOptions"-->
        <!--            :key="item.value"-->
        <!--            :label="item.label"-->
        <!--            :value="item.value">-->
        <!--          </el-option>-->
        <!--        </el-select>-->
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          type="textarea"
          :rows="8"
          placeholder="请输入内容"
          v-model="searchForm.description">
        </el-input>
      </el-form-item>


      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="searchForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="searchFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      departmentOptions: [],
      searchForm: {
        id: 0,
        name: '',
        description: '',
        status: 1,
      },
      dataRule: {
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '描述不能为空', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '状态不能为空', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.searchForm.id = id || 0;
      // 获取部门列表
      this.$http({
        url: this.$http.adornUrl('/sys/organizations/list'),
        method: 'get',
        params: this.$http.adornParams({})
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.departmentOptions = data.page.list.map(item => ({
            value: item.id,
            label: item.name
          }));
          console.log('Department options:', this.departmentOptions); // 添加调试信息
        } else {
          console.error('Failed to fetch department list:', data.msg);
        }
      }).then(() => {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs['searchForm'].resetFields();
        });
      }).then(() => {
        if (this.searchForm.id) {
          // 获取部门信息
          this.$http({
            url: this.$http.adornUrl('/sys/organizations/info'),
            method: 'get',
            params: this.$http.adornParams({id: this.searchForm.id})
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.searchForm.name = data.sysOrganizations.name;
              this.searchForm.description = data.sysOrganizations.description;
              this.searchForm.status = data.sysOrganizations.status;
            } else {
              console.error('Failed to fetch organization info:', data.msg);
            }
          }).catch(error => {
            console.error('Error fetching organization info:', error);
          });
        }
      });
    },
    // 表单提交
    searchFormSubmit() {
      this.$refs['searchForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/organizations/${!this.searchForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.searchForm.id || undefined,
              'name': this.searchForm.name,
              'description': this.searchForm.description,
              'status': this.searchForm.status,
            })
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refreshDataList');
                }
              });
            } else {
              this.$message.error(data.data);
            }
          }).catch(error => {
            console.error('Error submitting form:', error);
          });
        }
      });
    },
    // 计算部门名称
    getDepartmentName(organizationsId) {
      const department = this.departmentOptions.find(option => option.value === organizationsId)
      return department ? department.label : '未知部门'
    }
  }
}
</script>

<style>
.select-box {
  margin-left: 80px;
  margin-bottom: 10px;
}
</style>
